﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Threading;

namespace NBHF.Common
{
    public sealed class HttpHelper
    {
        /// <summary>
        /// 向指定地址发送POST请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string param, int timeout = 10000)
        {
            string strReturn = "";
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.MediaType = "application/json";
            request.Accept = "application/json";
            request.Method = "POST";
            request.Timeout = timeout;
            //request.KeepAlive = true;
            byte[] uploadBody = System.Text.Encoding.UTF8.GetBytes(param);
            request.ContentLength = uploadBody.Length;
            try
            {
                Stream smRequest = request.GetRequestStream();
                smRequest.Write(uploadBody, 0, uploadBody.Length);
                smRequest.Close();
                HttpWebResponse hwResponse = (HttpWebResponse)request.GetResponse();
                Stream smResponse = hwResponse.GetResponseStream();

                StreamReader smReader = new StreamReader(smResponse, Encoding.UTF8);
                strReturn = smReader.ReadToEnd().Trim();
                smReader.Close();
            }
            catch (Exception ex) { strReturn = ex.Message; }
            return strReturn;

        }


        public static string HttpPostWithFormParas(string url, string param, string[] headerkeys, string[] headervalues, string contenttype = "multipart/form-data")
        {
            string strReturn = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = contenttype;
            //request.MediaType = "application/json";
            //request.Accept = "application/json";
            request.Method = "POST";


            StringBuilder builder = new StringBuilder();

            if (headerkeys != null && headerkeys.Length > 0)
            {
                for (int i = 0; i < headerkeys.Length; i++)
                {
                    builder.Append("&");
                    builder.AppendFormat("{0}={1}", headerkeys[i], headervalues[i]);

                }
            }

            string parastring = builder.ToString().Substring(1);

            byte[] uploadBody = Encoding.UTF8.GetBytes(parastring);
            request.ContentLength = uploadBody.Length;

            try
            {
                Stream smRequest = request.GetRequestStream();
                smRequest.Write(uploadBody, 0, uploadBody.Length);
                smRequest.Close();
                HttpWebResponse hwResponse = (HttpWebResponse)request.GetResponse();
                Stream smResponse = hwResponse.GetResponseStream();

                StreamReader smReader = new StreamReader(smResponse, Encoding.UTF8);
                strReturn = smReader.ReadToEnd().Trim();
                smReader.Close();
            }
            catch (Exception ex) { strReturn = ex.Message; }
            return strReturn;
        }


        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开    
            return true;
        }
        #region HttpClient Get
        /// <summary>
        /// HttpClient实现Get请求
        /// </summary>
        public static string HttpClientGet(string url, Action<HttpClient> action = null)
        {
            var handler = new HttpClientHandler();//{ AutomaticDecompression = DecompressionMethods.GZip };
            using (var http = new HttpClient(handler))
            {
                http.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
                action?.Invoke(http);
                var response = http.GetAsync(url).Result;//拿到异步结果
                //Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
                //await异步读取最后的JSON（注意此时gzip已经被自动解压缩了，因为上面的AutomaticDecompression = DecompressionMethods.GZip）
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        #endregion

        #region HttpWebRequest实现Get请求
        /// <summary>
        /// HttpWebRequest实现Get请求
        /// </summary>
        public static string HttpWebRequestGet(string url, Action<HttpWebRequest> action = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 30 * 1000;
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            action?.Invoke(request);
            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }

        #endregion

        #region HttpClient实现Post请求
        /// <summary>
        /// HttpClient实现Post请求
        /// </summary>
        public static string HttpClientPost(string url, Dictionary<string, string> dic, Action<HttpClient> action = null)
        {
            HttpClientHandler handler = new HttpClientHandler();
            using (var http = new HttpClient(handler))
            {
                http.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(dic);
                action?.Invoke(http);
                var response = http.PostAsync(url, content).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        #endregion

        #region  HttpWebRequest实现post请求
        /// <summary>
        /// HttpWebRequest实现post请求
        /// </summary>
        public static string HttpWebRequestPost<T>(string url, T t, Action<HttpWebRequest> action = null)
        {
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            var postData = Newtonsoft.Json.JsonConvert.SerializeObject(t);
            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30 * 1000;//设置30s的超时
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            request.ContentType = "application/json";
            request.Method = "POST";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
            action?.Invoke(request);
            Stream postStream = request.GetRequestStream();
            postStream.Write(data, 0, data.Length);
            postStream.Close();
            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }

        /// <summary>
        /// HttpWebRequest实现post请求
        /// </summary>
        public static string HttpWebRequestPost<T>(string url, T t, string contentType, Action<HttpWebRequest> action = null)
        {
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            var postData = Newtonsoft.Json.JsonConvert.SerializeObject(t);
            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30 * 1000;//设置30s的超时
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            request.ContentType = contentType;
            request.Method = "POST";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
            action?.Invoke(request);
            Stream postStream = request.GetRequestStream();
            postStream.Write(data, 0, data.Length);
            postStream.Close();
            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
        #endregion

        #region HttpClient实现Put请求
        /// <summary>
        /// HttpClient实现Put请求
        /// </summary>
        public static string HttpClientPut(string url, Dictionary<string, string> dic)
        {
            HttpClientHandler handler = new HttpClientHandler();
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(dic);
                var response = http.PutAsync(url, content).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        #endregion

        #region  HttpWebRequest实现put请求
        /// <summary>
        /// HttpWebRequest实现put请求
        /// </summary>
        public static string HttpWebRequestPut<T>(string url, T t, Action<HttpWebRequest> action = null)
        {
            var postData = Newtonsoft.Json.JsonConvert.SerializeObject(t);

            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30 * 1000;//设置30s的超时
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            request.ContentType = "application/json";
            request.Method = "PUT";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(data, 0, data.Length);
            postStream.Close();

            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
        #endregion

        #region HttpClient实现Delete请求
        /// <summary>
        /// HttpClient实现Put请求
        /// 没放入数据
        /// </summary>
        public static string HttpClientDelete(string url, Dictionary<string, string> dic)
        {
            HttpClientHandler handler = new HttpClientHandler();
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(dic);
                var response = http.DeleteAsync(url).Result;
                //Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        #endregion

        #region  HttpWebRequest实现Delete请求
        /// <summary>
        /// HttpWebRequest实现put请求
        /// </summary>
        public static string HttpWebRequestDelete<T>(string url, T t, Action<HttpWebRequest> action = null)
        {
            var postData = Newtonsoft.Json.JsonConvert.SerializeObject(t);
            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30 * 1000;//设置30s的超时
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            request.ContentType = "application/json";
            request.Method = "Delete";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
            action?.Invoke(request);
            Stream postStream = request.GetRequestStream();
            postStream.Write(data, 0, data.Length);
            postStream.Close();
            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
        #endregion
    }
}
